<template>
    <div>
        <!-- 搜索卡片  查询条件：用户名、联系电话、性别、生日 -->
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="用户名">
                    <el-input type="text" placeholder="请输入用户名" v-model="queryForm.username" size="small" ></el-input>
                </el-form-item>
                <el-form-item label="电 话">
                    <el-input type="text" placeholder="输入联系电话" v-model="queryForm.mobile" size="small"></el-input>
                </el-form-item>
                <el-form-item label="住 址" >
                    <el-input type="text" placeholder="输入家庭住址" v-model="queryForm.address" size="small"></el-input>
                </el-form-item>
                <el-form-item label="性 别">
                    <el-select v-model="queryForm.sex" size="small">
                        <el-option value="男" label="男"></el-option>
                        <el-option value="女" label="女"></el-option>
                        <el-option value="未知" label="未知"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生 日" >
                    <el-date-picker value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择日期" v-model="queryForm.birthday"></el-date-picker>
                </el-form-item>
                <el-form-item label="身份权限">
                    <el-select v-model="queryForm.role" size="small">
                        <el-option value="SUPER_ADMIN" label="超级管理员"></el-option>
                        <el-option value="ADMIN" label="管理员"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
            :data="userList"
            v-loading="loading"
            border
            fit
            :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
            :cell-style="{padding:'5px 0px'}"
            @selection-change="handleSelectionChange"
            style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px" :selectable="checkSelectable"></el-table-column>
                <el-table-column label="头 像" align="center" width="80">
                    <template slot-scope="scope">
                        <el-avatar shape="square" :size="48" cover :src="'/imgs/avatar/'+scope.row.avatar"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="用户名"  align="center">
                    <template slot-scope="scope">
                    {{ scope.row.username }}
                    </template>
                </el-table-column>
                <el-table-column label="电 话" align="center">
                    <template slot-scope="scope">
                    <span>{{ scope.row.mobile }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="住 址" align="center">
                    <template slot-scope="scope">
                    <span>{{ scope.row.address }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="生 日" align="center">
                    <template slot-scope="scope">
                    <span>{{ formatDate(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="年 龄" align="center">
                    <template slot-scope="scope">
                    <span>{{ getAge(formatDate(scope.row.birthday, '{y}-{m}-{d}')) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="性 别" align="center">
                    <template slot-scope="scope">
                    <span>{{ scope.row.sex }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="身份权限" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.role === "SUPER_ADMIN" ? '超级管理员' : '管理员'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="启 用" align="center">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enable" active-color="#13ce66" 
                            inactive-color="#ff4949" active-value="1" inactive-value="0" disabled 
                            v-if="scope.row.role === 'SUPER_ADMIN'">
                        </el-switch>
                        <el-switch v-model="scope.row.enable" active-color="#13ce66" 
                            inactive-color="#ff4949" active-value="1" inactive-value="0"  
                            @change="changeEnable(scope.row)" v-if="scope.row.role !== 'SUPER_ADMIN'">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操 作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)" disabled v-if="scope.row.role === 'SUPER_ADMIN'">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)" disabled v-if="scope.row.role === 'SUPER_ADMIN'">删除</el-button>
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)" v-if="scope.row.role !== 'SUPER_ADMIN'">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)" v-if="scope.row.role !== 'SUPER_ADMIN'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                    :current-page="queryForm.pageNum" 
                    :page-size="queryForm.pageSize"
                    :total="total"
                    :page-sizes="[10,20,50,100]"
                    layout="total,sizes,prev,pager,next"
                    @current-change='handleCurrentChange'
                    @size-change='handleSizeChange'>
                </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show"  width="42%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules='rules' ref="submitForm">
                <el-row>
                    <el-col :span="24" style="text-align:center;">
                        <el-form-item>
                            <el-upload
                            class="avatar-uploader boxCardUploadImg "
                            action="/admin-api/img/upload/avatar"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :headers="headers"
                            name="file"
                            :before-upload="beforeAvatarUpload"
                            :on-progress="uploadAvatarProcess">
                            <img v-if="'/imgs/avatar/'+imageUrl" :src="'/imgs/avatar/'+imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <i class="el-icon-edit" ></i>
                            </el-upload>
                            <el-progress :style="progressStyle" :text-inside="true" :stroke-width="16" :percentage="loadProgress" :status="progressStatus"></el-progress>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="username">
                            <el-input type="text" placeholder="请输入用户名" v-model="submitForm.username"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密 码" prop="password">
                            <el-input type="password" placeholder="请输入密码" v-model="submitForm.password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="电 话" prop="mobile">
                            <el-input type="text" placeholder="请输入联系电话" v-model="submitForm.mobile"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="住 址" prop="address">
                            <el-input type="text" placeholder="请输入家庭住址" v-model="submitForm.address"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="性 别" prop="sex">
                            <el-select v-model="submitForm.sex" placeholder="请选择">
                                <el-option v-for="(item,index) in sexList" :key="'sex-'+index" :value="item" :label="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生 日" prop="birthday">
                            <el-date-picker value-format="yyyy-MM-dd" type="date" v-model="submitForm.birthday"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="身份权限" prop="role">
                            <el-input type="text" value="ADMIN"  v-model="submitForm.role" readonly></el-input>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right:40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { selectAll,getUser,addUser,updateUser,delUser } from '@/api/user'
    import { parseTime } from '@/utils/date'
    export default {
        name:'User',
        data(){
            //检查密码是否合法
            const checkPassword = (rule,value,callback)=>{
                //要求存在内容且长度必须在6-16位
                if (this.password == null && (value.length > 16 || value.length < 6)){
                    return callback(new Error('长度必须在6-16之间'))
                }
                if (this.password != value && (value.length > 16 || value.length < 6)){
                    return callback(new Error('长度必须在6-16之间'))
                }
                callback()
            }
            //检查电话是否合法
            const checkMobile = (rule,value,callback)=>{
                //不设置时通过
                if(!value){
                    return callback()
                }
                //设置时需要符合正则表达式则为合法电话
                let reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
                if(!reg.test(value)){
                    return callback(new Error('请输入合法电话'))
                }
                callback()
            }
            return{
                loading: true,
                userId:this.$Cookie.get("userId"),
                submitForm:{},
                title:"新增",
                show:false,
                total:120,
                queryForm:{
                    pageNum:1,
                    pageSize:10
                },
                sexList:['男','女','未知'],
                selectList:[],
                userList:[],
                password:'',
                rules:{
                    username:[
                        {required:true,message:'请输入用户名',trigger:'blur'},
                        {min:5,max:16,message:'长度必须在5-16之间',trigger:'blur'}
                    ],
                    password:[
                        {required:true,message:'请输入密码',trigger:'blur'},
                        {validator:checkPassword,trigger:'blur'}
                    ],
                    mobile:[
                        {validator:checkMobile,trigger:'blur'},
                    ],
                },
                address:{},
                fileName:null,
                imageUrl:'default.jpg',
                headers:{
                    Authorization: 'Bearer ' + this.$Cookie.get('login-token')
                },
                loadProgress: 0,
                progressStatus:null,
                progressStyle: "margin-top:5px;opacity: 0;"
            }
        },
        //创建网页后查询调用数据
        created(){
            this.getList()
        },
        methods:{
            //调用接口提交数据 - 进行添加和编辑操作的弹窗
            handleSubmit(){
                this.$refs['submitForm'].validate((valid)=>{
                    if(this.fileName){
                        this.submitForm.avatar = this.fileName
                    }
                    if(valid){
                        if(this.submitForm.id){
                            this.submitForm.updateBy = this.$Cookie.get("username")
                            updateUser(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }else{
                            this.submitForm.createBy = this.$Cookie.get("username")
                            addUser(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                        
                    }
                })
            },
            //重置搜索
            handleReset(){
                this.queryForm = {
                    pageNum:1,
                    pageSize:10
                }
                this.getList()
            },
            //按条件搜索
            handleSearch(){
                this.queryForm.pageNum = 1
                this.getList()
            },
            //修改每页大小
            handleSizeChange(pageSize){
                this.queryForm.pageSize = pageSize
                this.queryForm.pageNum = 1
                this.getList()
            },
            //当前页修改
            handleCurrentChange(pageNum){
                this.queryForm.pageNum = pageNum
                this.getList()
            },
            //调用接口分页查询用户数据
            getList(){
                this.loading = true
                selectAll(this.queryForm).then(res=>{
                    this.userList = res.data.records
                    this.total = res.data.total
                    this.loading = false
                }).catch(err=>{})
                
            },
            //删除 - 调用接口删除记录
            handleDelete(ids){
                this.$confirm("你确定删除id为"+ids+"的记录吗？","提示",{
                    cancelButtonText:"取消",
                    confirmButtonText:"确定",
                    type:"warning"
                }).then(()=>{
                    //调接口删除
                    delUser(ids).then(res => {
                        //提示删除成功
                        this.$message("删除成功")
                        //刷新列表
                        this.getList()
                    }).catch(err=>{
                        console.log(err)
                    })
                }).catch(()=>{})
            },
            //添加 - 打开添加弹窗
            handleAdd(){
                this.show = true
                this.title = "新增"
                this.imageUrl = 'default.jpg'
                this.submitForm={sex:'未知',role:'ADMIN'}
                this.address={}
            },
            //取消 - 关闭弹窗
            handleCancel(){
                this.show = false
            },
            //编辑 - 打开编辑弹窗
            handleEdit(id){
                getUser(id).then(res=>{
                    //调接口获取最新数据
                    this.title = "编辑"
                    this.show = true
                    this.submitForm = res.data
                    this.password = res.data.password
                    this.imageUrl = res.data.avatar
                    this.address = res.data.address
                }).catch(err=>{
                    console.log(err)
                })
                
            },
            //批量删除
            handleBatchDelete(){
                if(this.selectList){
                    let ids = this.selectList.map(o => {return o.id})
                    console.log('ids---------->',ids)
                    this.handleDelete(ids)
                }
            },
            //多选
            handleSelectionChange(val){
                this.selectList = val;
            },
            //选择时，如果为自己id则不能选中
            checkSelectable(row) {
                return row.id != this.userId
            },
            //头像上传前调用函数
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //上传头像进度
            uploadAvatarProcess(event, file, fileList) {
                this.progressStyle="margin-top:5px;opacity: 1;",
                this.loadProgress = parseInt(event.percent);
                if (this.loadProgress >= 100) {
                    this.progressStatus = "success"
                    this.loadProgress = 100
                    setTimeout( () => {this.progressStyle="margin-top:5px;opacity: 0;";this.progressStatus = null}, 1000) 
                }
            },
            //头像上传成功调用函数
            handleAvatarSuccess(res, file) {
                this.fileName = res.data
                this.imageUrl = this.fileName;
            },
            //时间格式化
            formatDate(value,format) {
                return parseTime(new Date(value),format)
            },
            //根据生日获取年龄
            getAge(value) {
                let birthdays = new Date(value.replace(/-/g, "/"))
                let d = new Date();
                let age = d.getFullYear() - birthdays.getFullYear() -  (d.getMonth() < birthdays.getMonth() || (d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate()) ? 1 : 0);
                return age
            },
            //修改启用状态
            changeEnable(data){
                data.updateBy = this.$Cookie.get("username")
                updateUser(data).catch(err=>{console.log(err)})
            }
        }
    }
</script>

<style scoped>
    .el-form-item{
        margin: 10px;
    }
    .address-form .el-select .el-input {
        border-color: #409EFF;
        width: 50px;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 20px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    border-radius: 20px;
    display: block;
  }
  
.boxCardUploadImg {
  width: 178px;
  height: 178px;
  border-radius: 20px;

  position: relative;
}
.boxCardUploadImg:hover {
  cursor: pointer;
}
.boxCardUploadImg:hover::after {
  content: '';
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 0;
  height: 100%;
  top: 0px;
  width: 100%;
  z-index: 99;
  border-radius: 20px;
}

.boxCardUploadImg i {
  display: none;
}
.boxCardUploadImg:hover i {
  position: absolute;
  font-size: 48px;
  display: initial;
  z-index: 999;
  color: #fff;
  
  top: 65px;
  left: 65px;
}
</style>